package cn.zhc.com.utils;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class UtilsWifi {
    private static UtilsWifi mUtilsWifi;
    private static WifiManager mWifiManager;
    private WifiLock mWifiLock;
    private List<ScanResult> mWifiList;//保存最近的访问点的wifi列表
    private List<WifiConfiguration> mWifiConfigurations;
    private WifiInfo mConnectionWifiInfo;//获取已经连接到成功的wifi

    private UtilsWifi(Context context) {
        super();
        mWifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
    }
    public synchronized static UtilsWifi getInstance(Context context){
        if (mUtilsWifi == null) {
            mUtilsWifi = new UtilsWifi(context);
        }
        
        return mUtilsWifi;
    }
    /**
     * 如果没有打开wifi,打开wifi
     * @return
     */
    public boolean openWifi(){
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
        try {
            
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return mWifiManager.isWifiEnabled();
        
    }
    
    /**
     * 关闭wifi
     */
    public void closeWifi(){
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }
    
    /**
     * 检查wifi的状态
     * @return
     */
    public int checkWifiState(){
        return mWifiManager.getWifiState();
    }
    
    /**
     * android为wifi提供了一种叫WifiLock的锁，能够阻止wifi进入睡眠状态，使wifi一直处于活跃状态。这种锁，在下载一个较大的文件的时候，比较适合使用。
     * @return
     */
    public void createWifiLock(){
        mWifiLock = mWifiManager.createWifiLock("test");
    }
    
    /**
     * 对wifi加锁，能够阻止wifi进入休眠状态
     */
    public void lockWifi(){
        if (mWifiLock!=null) {
            mWifiLock.acquire();
        }
    }
    
    /**
     * 释放wifilock
     */
    public void releaseWifi(){
        if (mWifiLock != null) {
            mWifiLock.release();
        }
    }
    
    /**
     * 扫描wifi，得到最近访问点扫描结果列表
     */
    public void startScan(){
        mWifiList = mWifiManager.getScanResults();
        mWifiConfigurations = mWifiManager.getConfiguredNetworks();
        //打印log
        if (mWifiList != null) {
            for (ScanResult scanResult : mWifiList) {
                Log.d("zhc", "SSID:"+scanResult.SSID+",BSSID:"+scanResult.BSSID);
                Log.d("zhc", "wifi功能的描述信息s："+scanResult.capabilities);
            }
            
        }else {
            Log.d("zhc", "wifi列表为null");
        }
    }
    /**
     * 获取扫描到的wifi列表
     * @return
     */
    public List<ScanResult> getWifiList() {
        return mWifiList;
    }
    /**
     * 从wifi的功能描述中，获取wifi对应的认证方式
     * @param capabilities wifi功能的描述
     * @return 如果返回"",则表示不需要密码
     */
    public String wifiEncryptType(String capabilities){
        ArrayList<String> encryptTypeList = new ArrayList<String>();
        encryptTypeList.add("WEP");
        encryptTypeList.add("WPA");
        encryptTypeList.add("WPA1");
        for (String encryptType : encryptTypeList) {
            if (capabilities.indexOf(encryptType) != -1) {
                return encryptType;
            }
        }
        return "";
        
    }
    
    /**
     * 获取当前连接的wifi
     */
    public void getConnectionWifiInfo(){
        mConnectionWifiInfo = mWifiManager.getConnectionInfo();
    }
    
    /**
     * 获取当前wifi的mac
     * @return
     */
    public String getBSSID() { // AP's mac-address
        return (mConnectionWifiInfo == null) ? "NULL" : mConnectionWifiInfo.getBSSID();
    }
    
    /**
     * Record the MAC address of the WLAN interface
     * @return
     */
    public String getMacAddress() {
        return (mConnectionWifiInfo == null) ? "NULL" : mConnectionWifiInfo.getMacAddress();
    }
    /**
     * 
     * 下面的这两个方法
     */
    public int getNetworkId() {
        return (mConnectionWifiInfo == null) ? 0 : mConnectionWifiInfo.getNetworkId();
    }
    public int getIPAddress() {
        return (mConnectionWifiInfo == null) ? 0 : mConnectionWifiInfo.getIpAddress();
    }
    /**
     * 获取当前ssid对应的WifiConfiguration是否存在，如果已经存在的话，不存在就返回null；获取所有的wificonfiguration列表，然后遍历对比当前的ssid，如果是返回当前ssid对应的
     * @param SSID
     * @return
     */
    private WifiConfiguration IsExsits(String SSID) { 
        
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        if (existingConfigs == null) {
            return null;
        }
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }
    
//  type:
//  1.WIFICIPHER_NOPASS
//  2.WIFICIPHER_WEP
//  3.WIFICIPHER_WPA 
    /**
     * 通过ssid,psw,type创建 一个新的WifiConfiguration
     * @param SSID
     * @param Password
     * @param Type
     * @return
     */
    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
        
        //判断当前是否已经连接到ssid，如果是，从WifiConfiguration列表中移除对应的WifiConfiguration
        WifiConfiguration tempConfig = this.IsExsits(SSID);
 
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        } else {
            Log.i("zhc", "IsExsits is null.");
        }
        
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        if (Type == 1) // WIFICIPHER_NOPASS
        {
            Log.i("zhc", "Type =1.");
//            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) // WIFICIPHER_WEP
        {
            Log.i("zhc", "Type =2.");
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) // WIFICIPHER_WPA
        {
 
            Log.i("zhc", "Type =3.");
            config.preSharedKey = "\"" + Password + "\"";
 
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }
    /**
     * 连接指定的ssid
     * @param ssid
     * @param passwd
     * @param encType
     */
    public void connectWifi(String ssid, String passwd, String encType) {

        mWifiManager.setWifiEnabled(true);

        // 1.WIFICIPHER_NOPASS
        // 2.WIFICIPHER_WEP
        // 3.WIFICIPHER_WPA
        int type = 1;
        if (passwd.equals("")) {
            type = 1;
        } else if (encType.equals("WEP")) {
            type = 2;
        } else if (encType.equals("WPA")) {
            type = 3;
        }

        int wcgID = mWifiManager.addNetwork(CreateWifiInfo(ssid, passwd, type));//通过获取到的网络的链接状态信息，来添加网络
        boolean b = mWifiManager.enableNetwork(wcgID, true);//连接一个连接（网络连接）
    }
    /**
     * 断开一个wifi连接
     * @param netId
     */
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }
    
    
    
    
}
